package com.allen_sauer.gwt.dnd.client.drop;

import java.util.List;

import com.allen_sauer.gwt.dnd.client.DragContext;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.AbsolutePanel;

import de.wbh.gwt.form.layouter.gwt.ui.view.widget.Field;
import de.wbh.gwt.form.layouter.shared.Box;

public class CustomDropController extends AbsolutePositionDropController {

	private final List<Box> boxes;

	public CustomDropController(AbsolutePanel dropTarget, List<Box> boxes) {
		super(dropTarget);
		this.boxes = boxes;
	}

	private Box getClosestBox(Draggable draggable) {
		int minDistance = Integer.MAX_VALUE;
		Box targetBox = null;
		for (Box box : this.boxes) {
			int distance = getDistance(draggable, box);
			if (distance < minDistance) {
				minDistance = distance;
				targetBox = box;
			}
		}
		return targetBox;
	}

	private int getDistance(Draggable draggable, Box box) {
		int deltaX = box.x - draggable.desiredX;
		int deltaY = box.y - draggable.desiredY;

		int distance = (int) Math.sqrt(deltaX * deltaX + deltaY * deltaY);
		return distance;
	}

	@Override
	public void onDrop(DragContext context) {
		for (Draggable draggable : this.draggableList) {
			draggable.widget.getElement().getStyle().setWidth(draggable.positioner.getOffsetWidth(), Unit.PX);
			draggable.widget.getElement().getStyle().setHeight(draggable.positioner.getOffsetHeight(), Unit.PX);
			System.out.println("set Height to " + draggable.positioner.getOffsetHeight());
			((Field) draggable.widget).setDropped(true);
		}
		super.onDrop(context);
	}

	@Override
	public void onMove(DragContext context) {
		super.onMove(context);
		for (Draggable draggable : this.draggableList) {
			Box closestBox = getClosestBox(draggable);
			if (getDistance(draggable, closestBox) < 100) {
				draggable.desiredX = closestBox.x;
				draggable.desiredY = closestBox.y;
				this.dropTarget.add(draggable.positioner, closestBox.x, closestBox.y);
				draggable.positioner.setPixelSize(closestBox.width, closestBox.height);
			}
		}
	}

}
